<?php

class CategoriasDespesasController extends Zend_Controller_Action
{

	public function init()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout->disableLayout();
	}

	public function indexAction()
	{
		$categoriasModel = new Application_Model_DbTable_CategoriasDespesas();
		$categorias = $categoriasModel->fetchAll(null, 'parent')->toArray();

		$new = array();
		foreach($categorias as $categoria){
			if($categoria['parent'] == NULL){
				$categoria['parent'] = 0;
			}
			$new[$categoria['parent']][] = $categoria;
		}

		$tree = $this->createTree($new, array($categorias[0]));
		$tree = $this->stripRoot($tree);
		$tree = $this->unsetRecursive($tree, 'parent');
		$tree = $this->addLeaf($tree);
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout->disableLayout();
		echo Zend_Json::encode($tree);
	}
	
	public function editAction(){
		$id = $this->_request->id;
		$newName = $this->_request->newName;
		
		$categoriasModel = new Application_Model_DbTable_CategoriasDespesas();
		if($categoriasModel->update(array('text' => $newName), 'id = ' . $id)){
			$json['success'] = true;
			$json['node']['id'] = $id;
			$json['node']['text'] = $newName;
		}
		else{
			$json['success'] = false;
		}
		
		echo Zend_Json::encode($json);
	}

	/**
	 * Solução encontrada aqui
	 * http://stackoverflow.com/questions/4196157/create-array-tree-from-array-list
	 * Enter description here ...
	 */
	private function createTree(&$list, $parent){
		$tree = array();
		foreach ($parent as $k=>$l){
			if(isset($list[$l['id']])){
				$l['children'] = $this->createTree($list, $list[$l['id']]);
			}

			$tree[] = $l;
		}

		return $tree;
	}

	private function stripRoot($array){
		return $array[0]['children'];
	}

	/**
	 * Solução encontrada em
	 * http://stackoverflow.com/questions/1708860/php-recursively-unset-array-keys-if-match
	 * Função para remover recursivamente um determinado campo de um array
	 * @param array $array
	 * @param string $key
	 */
	private function unsetRecursive(&$array, $key){
		unset($array[$key]);
		foreach($array as &$value){
			if(is_array($value)){
				$this->unsetRecursive($value, $key);
			}
		}

		return $array;
	}


	private function addLeaf(&$array){
		foreach($array as &$item){
			if(!isset($item['children'])){
				$item['leaf'] = "true";
			}
			else{
				$this->addLeaf($item['children']);
			}
		}
		
		return $array;
	}
}